package com.unittec.zk.provider.auth.controller;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.unittec.zk.provider.auth.entity.SysApplication;
import com.unittec.zk.provider.auth.service.LogService;
import com.unittec.zk.provider.auth.service.SysApplicationService;
import com.unittec.zk.provider.log.Log;
import com.unittec.zk.provider.utils.CopyListUtils;
import com.unittec.zk.provider.utils.CopyUtils;
import com.unittec.zk.provider.utils.ValidationUtils;
import com.unittec.zk.sdk.auth.domain.SysApplicationDto;
import com.unittec.zk.sdk.auth.request.Req101501;
import com.unittec.zk.sdk.auth.request.Req101502;
import com.unittec.zk.sdk.auth.request.Req101503;
import com.unittec.zk.sdk.auth.request.Req101504;
import com.unittec.zk.sdk.auth.request.Req101506;
import com.unittec.zk.sdk.auth.request.Req101509;
import com.unittec.zk.sdk.auth.request.Req101510;
import com.unittec.zk.sdk.auth.request.Req101511;
import com.unittec.zk.sdk.auth.request.Req101512;
import com.unittec.zk.sdk.auth.request.Req101513;
import com.unittec.zk.sdk.auth.response.Res101501;
import com.unittec.zk.sdk.auth.response.Res101502;
import com.unittec.zk.sdk.auth.response.Res101503;
import com.unittec.zk.sdk.auth.response.Res101504;
import com.unittec.zk.sdk.auth.response.Res101506;
import com.unittec.zk.sdk.auth.response.Res101509;
import com.unittec.zk.sdk.auth.response.Res101510;
import com.unittec.zk.sdk.auth.response.Res101511;
import com.unittec.zk.sdk.auth.response.Res101512;
import com.unittec.zk.sdk.auth.response.Res101513;
import com.unittec.zk.sdk.log.enums.LogOperateEnum;
import com.unittec.zk.sdk.log.enums.LogStatusEnum;
import com.unittec.zk.sdk.log.response.Res102020;
import com.unittec.zk.sdk.root.domain.GatewayRequest;
import com.unittec.zk.sdk.root.domain.Result;
import com.unittec.zk.sdk.root.enums.BizCode;
import com.unittec.zk.sdk.root.enums.BizCodeEnum;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author chengjie
 * @description 应用Controller
 * @date 2019/10/16
 */
@RestController
@Api(tags = "应用管理")
public class SysApplicationController {

    @Autowired
    Log log;

    @Autowired
    private SysApplicationService applicationService;
    @Autowired
    private LogService logService;

    @RequestMapping(value = "/101501", method = RequestMethod.POST)
    @ApiOperation(value = "应用校验", notes = "应用校验")
    @ResponseBody
    public Result<Res101501> getApplication(@RequestBody GatewayRequest<Req101501> req) {
        log.debug(req, "getApplication {}  ", "begin");
        try {
            Req101501 content = req.getContent();
            ValidationUtils.validateEntityStr(content);
            String ip = content.getIp();
            String appkey = content.getAppKey();
            String appCode = content.getAppCode();
            SysApplication sysApplication = applicationService.getApplicationByEntity(appCode, appkey);
            Res101501 res101501 = new Res101501();
            if (null == sysApplication) {
                return Result.error(req, "应用appCode不存在");
            }
            if (StringUtils.isNotBlank(sysApplication.getIp()) && !sysApplication.getIp().equals(ip)) {
                return Result.error(req, "应用ip:" + ip + "不匹配");
            }
            SysApplicationDto sysApplicationDto = new SysApplicationDto();
            CopyUtils.copyProperties(sysApplication, sysApplicationDto);
            res101501.setObj(sysApplicationDto);
            log.debug(req, "getApplication {}  ", "end");
            return Result.success(req, res101501);
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
    }

    @RequestMapping(value = "/101502", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "应用分页列表", notes = "应用分页列表")
    public Result<Res101502> appListForPage(@RequestBody GatewayRequest<Req101502> req) {
        log.debug(req, "appListForPage{}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101502 res101502 = null;
        try {
            IPage<Map<String, Object>> appList = applicationService.appListForPage(req.getContent());
            res101502 = new Res101502();
            res101502.setPage(appList);
            bizCodeEnum = BizCode.SUCCESS;

        } catch (Exception e) {
            log.error(req, e.toString(), e);
        }
        log.debug(req, "appListForPage {}  ", "end");

        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101502);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101503", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "应用删除", notes = "应用删除")
    public Result<Res101503> delApp(@RequestBody GatewayRequest<Req101503> req) {
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        log.debug(req, "delApp {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        try {
            boolean ret = applicationService.removeById(req.getContent().getId());
            if (ret) {
                bizCodeEnum = BizCode.SUCCESS;
                log.addOperateLog("101503", JSON.toJSONString(req), "应用删除", "应用删除成功", LogOperateEnum.LOG_DEL.getCode(),
                    LogStatusEnum.SUCCESS.getCode(), startLogTime);
            } else {
                bizCodeEnum = BizCode.ERROR;
                log.addOperateLog("101503", JSON.toJSONString(req), "应用删除", "应用删除失败：" + bizCodeEnum.getCode(),
                    LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.toString());
        }
        log.debug(req, "delApp {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101504", method = RequestMethod.POST)
    @ApiOperation(value = "应用信息修改", notes = "应用信息修改")
    @ResponseBody
    public Result<Res101504> updateApp(@RequestBody GatewayRequest<Req101504> req) {
        log.debug(req, "updateApp {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        long startLogTime = System.currentTimeMillis();
        Res101504 res101504 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysApplication sysApplication = applicationService.getById(req.getContent().getId());
            if (sysApplication != null) {
                BeanUtils.copyProperties(req.getContent(), sysApplication);
                boolean ok = applicationService.updateById(sysApplication);
                if (ok) {
                    res101504 = new Res101504();
                    res101504.setIsSuccess(true);
                    bizCodeEnum = BizCode.SUCCESS;
                    log.addOperateLog("205503", JSON.toJSONString(req), "应用信息修改", "应用信息修改成功",
                        LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
                }
            } else {
                bizCodeEnum = BizCode.NOT_ROLE;
                log.addOperateLog("205503", JSON.toJSONString(req), "应用信息修改", "应用信息修改失败：" + bizCodeEnum.getCode(),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
        }
        log.debug(req, "updateApp {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101504);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101506", method = RequestMethod.POST)
    @ApiOperation(value = "应用信息添加", notes = "应用信息添加")
    @ResponseBody
    public Result<Res101506> addApp(@RequestBody GatewayRequest<Req101506> req) {
        log.debug(req, "addApp {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        long startLogTime = System.currentTimeMillis();
        Res101506 res101506 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysApplication sysApplication = new SysApplication();
            BeanUtils.copyProperties(req.getContent(), sysApplication);
            boolean ok = applicationService.save(sysApplication);
            if (ok) {
                res101506 = new Res101506();
                res101506.setIsSuccess(true);
                bizCodeEnum = BizCode.SUCCESS;
                log.addOperateLog("101506", JSON.toJSONString(req), "应用信息添加", "应用信息添加成功",
                    LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101506", JSON.toJSONString(req), "应用信息添加", "应用信息添加失败：" + bizCodeEnum.getCode(),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
        }
        log.debug(req, "addApp {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101506);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    /**
     * 创建应用日志名
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/101509", method = RequestMethod.POST)
    @ApiOperation(value = "创建应用日志名", notes = "创建应用日志名")
    public Result<Res101509> createAppLogName(@RequestBody GatewayRequest<Req101509> req) {
        log.debug(req, "createAppLogName {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        try {
            Req101509 content = req.getContent();
            ValidationUtils.validateEntityStr(content);
            Boolean aBoolean = logService.appCreateLog(content.getAppId(), content.getLogName());
            Res101509 res = new Res101509();
            res.setIsSuccess(aBoolean);
            if (aBoolean) {
                log.addOperateLog("101509", JSON.toJSONString(req), "创建应用日志名成功", BizCode.SUCCESS.getMessage(),
                    LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            } else {
                log.addOperateLog("101509", JSON.toJSONString(req), "创建应用日志名失败", BizCode.ERROR.getMessage(),
                    LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            }
            log.debug(req, "createAppLogName {}  ", "end-------");
            return Result.success(req, res);
        } catch (Exception e) {
            log.addOperateLog("101509", JSON.toJSONString(req.getContent()), "创建应用日志名失败", log.buildErrmsg(e),
                LogOperateEnum.LOG_LIST.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            log.error(req, BizCode.UPDATE_ERROR.getMessage(), e);
            return Result.error(req, BizCode.UPDATE_ERROR.getCode(),
                BizCode.SAVE_ERROR.getMessage() + " " + e.getLocalizedMessage());
        }
    }

    /**
     * 根据应用appID获取各个服务的日志级别
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/101510", method = RequestMethod.POST)
    @ApiOperation(value = "根据应用appID获取各个服务的日志级别", notes = "根据应用appID获取各个服务的日志级别")
    public Result<Res101510> getLogLevelListByAppId(@RequestBody GatewayRequest<Req101510> req) {
        log.debug(req, "getLogLevelListByAppId {}  ", "begin");
        try {
            Req101510 content = req.getContent();
            ValidationUtils.validateEntityStr(content);
            List<Res102020> logLevelListByAppId = logService.getLogLevelListByAppId(content.getAppId());
            Res101510 res101510 = new Res101510();
            res101510.setList(logLevelListByAppId);
            log.debug(req, "getLogLevelListByAppId {}  ", "end");
            return Result.success(req, res101510);
        } catch (Exception e) {
            log.error(req, BizCode.LIST_ERROR.getMessage(), e);
            return Result.error(req, BizCode.LIST_ERROR.getCode(),
                BizCode.LIST_ERROR.getMessage() + " " + e.getLocalizedMessage());
        }
    }

    /**
     * 修改应用服务日志级别
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/101511", method = RequestMethod.POST)
    @ApiOperation(value = "修改应用服务日志级别", notes = "修改应用服务日志级别")
    public Result<Res101511> updateServiceLogLevel(@RequestBody GatewayRequest<Req101511> req) {
        log.debug(req, "updateServiceLogLevel {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        try {
            Req101511 content = req.getContent();
            ValidationUtils.validateEntityStr(content);
            Boolean aBoolean =
                logService.setLogLevel(content.getServiceIds(), content.getAppId(), content.getLogLevelE());
            Res101511 res = new Res101511();
            res.setIsSuccess(aBoolean);
            if (aBoolean) {
                log.addOperateLog("101511", JSON.toJSONString(req), "修改应用服务日志级别成功", BizCode.SUCCESS.getMessage(),
                    LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            } else {
                log.addOperateLog("101511", JSON.toJSONString(req), "修改应用服务日志级别失败", BizCode.ERROR.getMessage(),
                    LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            }
            log.debug(req, "updateServiceLogLevel {}  ", "end-------");
            return Result.success(req, res);
        } catch (Exception e) {
            log.addOperateLog("101511", JSON.toJSONString(req.getContent()), "修改应用服务日志级别失败", log.buildErrmsg(e),
                LogOperateEnum.LOG_LIST.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            log.error(req, BizCode.UPDATE_ERROR.getMessage(), e);
            return Result.error(req, BizCode.UPDATE_ERROR.getCode(),
                BizCode.SAVE_ERROR.getMessage() + " " + e.getLocalizedMessage());
        }
    }

    /**
     * 根据应用appID获取日志名
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/101512", method = RequestMethod.POST)
    @ApiOperation(value = "根据应用appID获取日志名", notes = "根据应用appID获取日志名")
    public Result<Res101512> getLogNameByAppId(@RequestBody GatewayRequest<Req101512> req) {
        log.debug(req, "getLogNameByAppId {}  ", "begin");
        try {
            Req101512 content = req.getContent();
            ValidationUtils.validateEntityStr(content);
            String logNameByAppId = logService.getLogNameByAppId(content.getAppId());
            Res101512 res101512 = new Res101512();
            res101512.setObj(logNameByAppId);
            log.debug(req, "getLogNameByAppId {}  ", "end");
            return Result.success(req, res101512);
        } catch (Exception e) {
            log.error(req, BizCode.LIST_ERROR.getMessage(), e);
            return Result.error(req, BizCode.LIST_ERROR.getCode(),
                BizCode.LIST_ERROR.getMessage() + " " + e.getLocalizedMessage());
        }
    }

    /**
     * 根据获取所有应用
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/101513", method = RequestMethod.POST)
    @ApiOperation(value = "根据获取所有应用", notes = "根据获取所有应用")
    public Result<Res101513> getAllApplication(@RequestBody GatewayRequest<Req101513> req) {
        log.debug(req, "getAllApplication {}  ", "begin");
        try {
            List<SysApplication> all = applicationService.findAll();
            List<SysApplicationDto> list = CopyListUtils.copyList(all, SysApplicationDto.class);
            Res101513 res101513 = new Res101513();
            res101513.setObj(list);
            log.debug(req, "getAllApplication {}  ", "end");
            return Result.success(req, res101513);
        } catch (Exception e) {
            log.error(req, BizCode.LIST_ERROR.getMessage(), e);
            return Result.error(req, BizCode.LIST_ERROR.getCode(),
                BizCode.LIST_ERROR.getMessage() + " " + e.getLocalizedMessage());
        }
    }
}
